import xml.etree.ElementTree as ET
import pickle
import os
from os import listdir, getcwd
from os.path import join

# classes也需要根据自己的实际情况修改
classes = ["dog",
           "person",
           "cat",
           "tv",
           "car",
           "meatballs",
           "marinara sauce",
           "tomato soup",
           "chicken noodle soup",
           "french onion soup",
           "chicken breast",
           "ribs",
           "pulled pork",
           "hamburger",
           "cavity"
           ]


# def convert(size, box):
#     dw = 1. / size[0]
#     dh = 1. / size[1]
#     x = (box[0] + box[1]) / 2.0
#     y = (box[2] + box[3]) / 2.0
#     w = box[1] - box[0]
#     h = box[3] - box[2]
#     x = x * dw
#     w = w * dw
#     y = y * dh
#     h = h * dh
#     return (x, y, w, h)
#
#
# import os
# import xml.etree.ElementTree as ET
#
#
# def convert(size, box):
#     """将边界框坐标从VOC格式转换为YOLO格式"""
#     dw = 1. / size[0]
#     dh = 1. / size[1]
#     x = (box[0] + box[1]) / 2.0
#     y = (box[2] + box[3]) / 2.0
#     w = box[1] - box[0]
#     h = box[3] - box[2]
#     x = x * dw
#     w = w * dw
#     y = y * dh
#     h = h * dh
#     return round(x, 6), round(y, 6), round(w, 6), round(h, 6)
#
#
# # 读取文件夹下所有xml文件
# xml_path = "./annotation/"
# files = os.listdir(xml_path)
# # files.sort(key=lambda x: int(x.split('.')[0]))
# files = [f for f in files if f.endswith(".xml")]
#
# for file in files:
#     # 解析XML文件
#     tree = ET.parse(xml_path + file)
#     root = tree.getroot()
#
#     # 获取图像宽度和高度
#     size = root.find("size")
#     w = int(size.find("width").text)
#     h = int(size.find("height").text)
#     c = int(size.find("depth").text)
#
#     # 遍历XML文件中的每个目标
#     for obj in root.iter("object"):
#         cls = obj.find("name").text
#         cls_id = classes.index(cls)
#         xmlbox = obj.find("bndbox")
#         b = (
#             float(xmlbox.find("xmin").text),
#             float(xmlbox.find("xmax").text),
#             float(xmlbox.find("ymin").text),
#             float(xmlbox.find("ymax").text),
#         )
#         # 转换坐标
#         bb = convert((w, h), b)
#
#         # 写入YOLO格式标注文件
#         hh = file[:-4]
#         with open('./label/' + file[:-4] + ".txt", "w") as f:
#             f.write(str(cls_id) + f" {cls} {bb[0]} {bb[1]} {bb[2]} {bb[3]}\n")


def convert(size, box):
    dw = 1. / size[0]
    dh = 1. / size[1]
    x = (box[0] + box[1]) / 2.0
    y = (box[2] + box[3]) / 2.0
    w = box[1] - box[0]
    h = box[3] - box[2]
    x = x * dw
    w = w * dw
    y = y * dh
    h = h * dh
    return (x, y, w, h)


def convert_annotation(image_id):
    if not os.path.exists('annotation/%s.xml' % (image_id)):
        return

    in_file = open('annotation/%s.xml' % (image_id))

    out_file = open('label/%s.txt' % (image_id), 'w')
    tree = ET.parse(in_file)
    root = tree.getroot()
    size = root.find('size')
    w = int(size.find('width').text)
    h = int(size.find('height').text)

    for obj in root.iter('object'):
        cls = obj.find('name').text
        if cls not in classes:
            continue
        cls_id = classes.index(cls)
        xmlbox = obj.find('bndbox')
        b = (float(xmlbox.find('xmin').text), float(xmlbox.find('xmax').text), float(xmlbox.find('ymin').text),
             float(xmlbox.find('ymax').text))
        bb = convert((w, h), b)
        out_file.write(str(cls_id) + " " + " ".join([str("{:.6f}".format(round(a, 6))) for a in bb]) + '\n')


for image in os.listdir('annotation'):
    image_id = image.split('.')[0]
    convert_annotation(image_id)
